<?php
/**
 * 注意：本内容仅限于博也公司内部传阅,禁止外泄以及用于其他的商业目的
 * @author    hebidu<346551990@qq.com>
 * @copyright 2018 www.itboye.com Boye Inc. All rights reserved.
 * @link      http://www.itboye.com/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 * Revision History Version
 ********1.0.0********************
 * file created @ 2018-03-17 10:05
 *********************************
 ********1.0.1********************
 *
 *********************************
 */

namespace by\component\tailong_bank\api_proxy;


use by\component\tailong_bank\api\ApproveDevApi;
use by\component\tailong_bank\api\BaseApi;
use by\component\tailong_bank\cache\FsCachePool;
use by\component\tailong_bank\context\BaseContext;
use by\component\tailong_bank\req\ApproveDevReq;
use by\component\tailong_bank\resp\ApproveDevResp;
use by\infrastructure\base\CallResult;
use by\infrastructure\helper\CallResultHelper;

/**
 * Class BaseProxy
 * @property BaseApi $api
 * @property BaseContext $context
 * @package by\component\tailong_bank\api_proxy
 */
class BaseProxy
{

    protected $api;
    protected $context;

    /**
     * BaseProxy constructor.
     * @param $context
     */
    public function __construct($context)
    {
        $this->context = $context;
    }

    /**
     * @return BaseApi
     */
    public function getApi()
    {
        return $this->api;
    }

    /**
     * @param BaseApi $api
     */
    public function setApi($api)
    {
        $this->api = $api;
    }

    /**
     * @param BaseContext $context
     * @return CallResult
     * @throws \ErrorException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getAppAccessToken(BaseContext $context)
    {
        $api = new ApproveDevApi(new FsCachePool($context->getCachePath()));
        $random = time() . rand(1000, 9999);
        $seqNo = date('YmdHis');
        $req = new ApproveDevReq();
        $req->setRandom($random);
        $req->setSeqNo($seqNo);
        $result = $api->call($req, $context);
        $data = $result->getData();
        if ($result->isSuccess() && $data instanceof ApproveDevResp) {
            return CallResultHelper::success($data->getAppAccessToken());
        } else {
            return CallResultHelper::fail($result->getMsg(), $result->getData());
        }
    }
}